package com.example.gateway.examples;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 简单网关示例
 * <p>
 * 功能说明：
 * 1. 演示基本的网关路由配置
 * 2. 展示如何配置断言和过滤器
 * 3. 提供负载均衡和服务发现集成
 *
 * @author Spring Cloud Demo
 * @version 1.0
 * @since 2024-01-01
 */
@SpringBootApplication
public class SimpleGatewayExample {

    public static void main(String[] args) {
        SpringApplication.run(SimpleGatewayExample.class, args);
        System.out.println("🚀 简单网关示例启动成功！");
    }

    /**
     * 网关配置类
     * 演示基本的路由配置
     */
    @Configuration
    public static class GatewayConfig {

        /**
         * 配置基本路由规则
         *
         * @param builder 路由构建器
         * @return 路由定位器
         */
        @Bean
        public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
            return builder.routes()
                    // 示例1：基本路径路由
                    .route("basic-route", r -> r
                            .path("/api/users/**")
                            .uri("http://localhost:8081")
                    )

                    // 示例2：带过滤器的路由
                    .route("filtered-route", r -> r
                            .path("/api/products/**")
                            .filters(f -> f
                                    .stripPrefix(1)
                                    .addRequestHeader("X-Source", "gateway")
                            )
                            .uri("http://localhost:8082")
                    )

                    // 示例3：负载均衡路由
                    .route("load-balanced-route", r -> r
                            .path("/api/orders/**")
                            .uri("lb://order-service")
                    )

                    // 示例4：条件路由
                    .route("conditional-route", r -> r
                            .path("/api/admin/**")
                            .and()
                            .header("X-Role", "admin")
                            .uri("http://localhost:8083")
                    )

                    .build();
        }
    }
} 